package com.zzyang.mybatis.jdbc.loadbalance;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 轮询
 *
 * @author zhuoziyang
 * @date 2021/4/9 12:37
 */
public class RoundRobinLoadBalance extends AbstractLoadBalance {

    private AtomicInteger count = new AtomicInteger();

    @Override
    protected String doSelect(List<String> dataSourceIds) {
        int size = dataSourceIds.size();
        int num = count.getAndIncrement();
        if (num < 0) {
            synchronized (this) {
                int value = count.intValue();
                if (value < 0) {
                    count.set(0);
                }
                num = count.getAndIncrement();
            }
        }
        int index = num % size;
        return dataSourceIds.get(index);
    }

}
